<?php
declare (strict_types = 1);
namespace app\http;

use app\api\logic\LotteryLogic;
use think\worker\Server;
use Workerman\Lib\Timer;

class Worker extends Server {
    protected $socket = 'websocket://0.0.0.0:2346';
    public function __construct() {
        parent::__construct();
        $this->onWorkerStart();

    }
    public function onWorkerStart() {

        $this->add_timer();
    }
    public function add_timer() {
        #设置每60秒执行一次定时任务
        /**
         *前端启动方式：
        // 假设服务端ip为127.0.0.1
        ws = new WebSocket("ws://127.0.0.1:2347");
        ws.onopen = function() {
        alert("连接成功");
        };
        ws.onmessage = function(e) {
        alert("收到服务端的消息：" + e.data);
        };
         */

        Timer::add(1, array($this, 'index'), array(), true);
        //Timer::add(60, array($this, 'bonus'), array(), true);
    }
    /**
     * @param $connection
     * @param $data 142842567084ds
     */
    public function onMessage($connection, $data) {

        $message = [
            'application_ids.require'  => '应用类型必须选定',
            'upgrade_start.require'    => '升级开始时间不能为空',
            'upgrade_start.dateFormat' => '时间格式不正确',
            'upgrade_end.dateFormat'   => '时间格式不正确',
            'upgrade_end.gt'           => '结束时间必须大于开始时间',
            'upgrade_end.require'      => '升级结束时间不能为空',
            'tips.require'             => '升级备注不能为空',
            'users_ids.require'        => '请选择升级用户或类型',
            'close_type.require'       => '必须选择关闭某个端',
        ];

        $connection->send(json_encode($message));

    }

    /**
     * 显示资源列表
     *
     * @return \think\Response
     */
    public function index() {

        $time = time();

        //每天7点执行任务 82800
        if ($time % 86400 == 82800) {

            $bonus_logic = new LotteryLogic();
            $lottery_id  = 'ssq';
            $bonus_logic->lottery_buy($lottery_id);
            $bonus_logic->bonus($lottery_id);

            file_put_contents('a.log', date('Y-m-d H:i:s', time()) . '执行了一次双色球开奖任务' . $time % 86400 . PHP_EOL, FILE_APPEND);

            file_put_contents('a.log', date('Y-m-d H:i:s', time()) . '执行了一次双色球购买任务' . PHP_EOL, FILE_APPEND);

        }

    }

}